/*
 * DestinationScreen.java
 *
 */
package com.gpsnav.screen;

import net.rim.device.api.ui.*;
import net.rim.device.api.ui.container.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.component.AutoTextEditField;
import javax.microedition.location.Coordinates;
import net.rim.device.api.ui.text.NumericTextFilter;
import net.rim.device.api.util.*;
import com.gpsnav.bo.Options;
import com.gpsnav.bo.Waypoint;
import com.gpsnav.dao.OptionsDAO;
import com.gpsnav.dao.WaypointsDAO;
import com.gpsnav.util.CoordinateConversion;
import com.gpsnav.util.ResizableChoiceField;

import javax.microedition.location.*;

public class MarkWaypointScreen extends MainScreen {

    AutoTextEditField nameField = new AutoTextEditField("Waypoint Name:   ","");
    AutoTextEditField latitudeField = new AutoTextEditField("-DD.DDDDDD:   ","",10,BasicEditField.FILTER_REAL_NUMERIC);
    AutoTextEditField longitudeField = new AutoTextEditField("-DDD.DDDDDD:  ", "", 11, BasicEditField.FILTER_REAL_NUMERIC);

    AutoTextEditField latitudeDecField = new AutoTextEditField("","",7,BasicEditField.FILTER_REAL_NUMERIC);
    AutoTextEditField longitudeDecField = new AutoTextEditField("", "", 7, BasicEditField.FILTER_REAL_NUMERIC);

    AutoTextEditField latitudeIntField = new AutoTextEditField("","",2,BasicEditField.FILTER_INTEGER);
    AutoTextEditField longitudeIntField = new AutoTextEditField("", "", 3, BasicEditField.FILTER_INTEGER);

    String[] latDir = {"N","S"};
    String[] lonDir = {"E","W"};
//    ObjectChoiceField latitudeDirectionField = new ObjectChoiceField("", latDir,0);
//    ObjectChoiceField longitudeDirectionField = new ObjectChoiceField("", lonDir,0);
    ResizableChoiceField latitudeDirectionField = new ResizableChoiceField("", latDir,0);
    ResizableChoiceField longitudeDirectionField = new ResizableChoiceField("", lonDir,0);

    NumericChoiceField MGRSGridZoneNumField = new NumericChoiceField("",1,60,1);
    String[] gridAlphaChoices = {"C","D","E","F","G","H","J","K","L","M","N","P","Q","R","S","T","U","V","W","X"};
    ResizableChoiceField MGRSGridZoneAlphaField = new ResizableChoiceField("", gridAlphaChoices,0);

    AutoTextEditField MGRSGridField = new AutoTextEditField("", "", 11, BasicEditField.FILTER_UPPERCASE);

    AutoTextEditField MGRSNorthingField = new AutoTextEditField("", "", 11, BasicEditField.FILTER_REAL_NUMERIC);
    AutoTextEditField MGRSEastingField = new AutoTextEditField("", "", 11, BasicEditField.FILTER_REAL_NUMERIC);

   // Coordinates destination = null;
    Waypoint currentWaypoint = null;
    Options options = new Options();
    OptionsDAO oDao = new OptionsDAO();


    public MarkWaypointScreen() {
        options = oDao.loadOptions();
        //options = o;
//        latitudeField.setFilter(BasicEditField.FILTER_REAL_NUMERIC));
//        longitudeField.setFilter(new NumericTextFilter(NumericTextFilter.ALLOW_DECIMAL));

         add(nameField);
         switch (Options.getCoordFormat()) {
            case 0: //HorizontalFieldManager h = new HorizontalFieldManager();
                    add(new LabelField("Longitude(dd.ddddd)"));
                    add(latitudeField);
                    //add(h);
                    add(new SeparatorField());
                    //h = new HorizontalFieldManager();
                    add(new LabelField("Latitude(dd.ddddd)"));
                    add(longitudeField);
                    //add(h);
                    add(new SeparatorField());
                    break;

            case 1: HorizontalFieldManager f1 = new HorizontalFieldManager();
                    add(new LabelField("Enter your Destination Coordinates "));
                    add(new LabelField("Latitude"));
                    f1.add(new LabelField("   "));
                    VerticalFieldManager v1 = new VerticalFieldManager();

                    v1.add(new LabelField("N/S:   "));
                    v1.add(new LabelField("dd:   "));
                    v1.add(new LabelField("mm.mmmm:   "));
                    f1.add(v1);

                    v1 = new VerticalFieldManager();
                    v1.add(latitudeDirectionField);
                    v1.add(latitudeIntField);
                    v1.add(latitudeDecField);
                    f1.add(v1);
                    add(f1);

                    add(new SeparatorField());

                    f1 = new HorizontalFieldManager();
                    add(new LabelField("Longitude"));
                    f1.add(new LabelField("   "));
                    v1 = new VerticalFieldManager();
                    v1.add(new LabelField("E/W:   "));
                    v1.add(new LabelField("ddd:   "));
                    v1.add(new LabelField("mm.mmmm:   "));
                    f1.add(v1);

                    v1 = new VerticalFieldManager();
                    v1.add(longitudeDirectionField);
                    v1.add(longitudeIntField);
                    v1.add(longitudeDecField);
                    f1.add(v1);
                    add(f1);
                    add(new SeparatorField());
                    break;
            case 2: //HorizontalFieldManager h2 = new HorizontalFieldManager();
                    add(new LabelField("MGRS: "));
                    add(MGRSGridZoneNumField);
                    add(MGRSGridZoneAlphaField);
                    add(MGRSGridField);
                    add(MGRSEastingField);
                    add(new LabelField("E"));
                    add(MGRSNorthingField);
                    add(new LabelField("N"));
                    //add(h2);
                    break;
         }

//        add(latitudeField);
//        add(longitudeField);

    }

    public void setWaypoint(Coordinates loc) {

        Coordinates c = loc;
        //destination = dest;
        if (c == null) {
            c = new Coordinates(0,0,0);
        }

        Waypoint wp = new Waypoint("WPT-"+WaypointsDAO.getNextId(), c.getLatitude(), c.getLongitude(), c.getAltitude());
        //wp = new Waypoint("WPT-"+WaypointsDAO.getNextId(), 89,76,45);
        setWaypoint(wp);
    }

    public void setWaypoint(Waypoint wp) {
        currentWaypoint = wp;
        setFields(wp);
    }

    public void setFields(Waypoint wp) {

        //destination = dest;
        if (wp != null) {
            nameField.setText(wp.getName());
          switch (Options.getCoordFormat()) {

              case 0: latitudeField.setText(Double.toString(wp.getLatitude()));
                      longitudeField.setText(Double.toString(wp.getLongitude()));
                      break;

              case 1: String lat = Coordinates.convert(Math.abs(wp.getLatitude()),Coordinates.DD_MM);
                      String lon = Coordinates.convert(Math.abs(wp.getLongitude()),Coordinates.DD_MM);

                      latitudeDirectionField.setSelectedIndex((wp.getLatitude() > 0) ?0 : 1);
                      longitudeDirectionField.setSelectedIndex((wp.getLongitude() > 0) ?0 : 1);

                      latitudeIntField.setText(lat.substring(0,lat.indexOf(":")));
                      latitudeDecField.setText(lat.substring(lat.indexOf(":")+1,lat.length()));

                      longitudeIntField.setText(lon.substring(0,lon.indexOf(":")));
                      longitudeDecField.setText(lon.substring(lon.indexOf(":")+1,lon.length()));
                      break;

              case 2: CoordinateConversion conv = new CoordinateConversion();
                      String mgrutm = conv.latLon2MGRUTM(wp.getLatitude(),wp.getLongitude());
//System.out.println("mgrutm="+mgrutm);
                      int zone = Integer.parseInt(mgrutm.substring(0, 2));
//System.out.println("zone="+zone);
                      MGRSGridZoneNumField.setSelectedValue(zone);

                      String latZone = mgrutm.substring(2, 3);
//System.out.println("latZone="+latZone);
                      for (int i=0;i<gridAlphaChoices.length;i++) {
                          if (latZone.equals(gridAlphaChoices[i])) {
                              MGRSGridZoneAlphaField.setSelectedIndex(i);
//System.out.println("latZonefound index="+i);
                          }
                      }

                      String digraph1 = mgrutm.substring(3, 4);
//System.out.println("digraph1="+digraph1);
                      String digraph2 = mgrutm.substring(4, 5);
//System.out.println("digraph2="+digraph2);
                      MGRSGridField.setText(digraph1+digraph2);

                      MGRSEastingField.setText(mgrutm.substring(5, 10));
//System.out.println("northing="+mgrutm.substring(5, 10));
                      MGRSNorthingField.setText(mgrutm.substring(10, 15));
//System.out.println("easting="+mgrutm.substring(10, 15));
                      break;
              }
        }
    }

//    public Coordinates getDestination () {
//      return destination;
//    }

    public MenuItem storeMenuItem = new MenuItem("Save Waypoint", 1,1){
        public void run(){
            save();
             UiApplication.getUiApplication().popScreen();
        }
    };


    public void save() {
            Coordinates coord = new Coordinates(0,0,0);
           switch (Options.getCoordFormat()) {
             case 0: double destLat =  Double.parseDouble(latitudeField.getText());
                     double destLong =  Double.parseDouble(longitudeField.getText());
                      coord = new Coordinates(destLat, destLong, 0);
                     break;

             case 1: double lat = Double.parseDouble(latitudeDecField.getText());
                     lat /= 60d;
                     lat += Double.parseDouble(latitudeIntField.getText());
                     if (latitudeDirectionField.getSelectedIndex() == 1) {
                        lat *=  -1d;
                     }

                     double lon = Double.parseDouble(longitudeDecField.getText());
                     lon /= 60d;
                     lon += Double.parseDouble(longitudeIntField.getText());
                     if (longitudeDirectionField.getSelectedIndex() == 1) {
                        lon *=  -1d;
                     }
                     coord = new Coordinates(lat, lon, 0);
                     break;

             case 2: StringBuffer sb = new StringBuffer();
                     int gridZone =  MGRSGridZoneNumField.getSelectedValue();
                     if (gridZone < 10) {
                       sb.append("0" + gridZone);
                     } else {
                       sb.append(""+gridZone);
                     }
                     sb.append((String)MGRSGridZoneAlphaField.getChoice(MGRSGridZoneAlphaField.getSelectedIndex()));
                     sb.append(MGRSGridField.getText());
                     sb.append(MGRSEastingField.getText());
                     sb.append(MGRSNorthingField.getText());
//System.out.println("mgrs="+sb.toString());
                     CoordinateConversion conv = new CoordinateConversion();
                     double[] c = conv.mgrutm2LatLon(sb.toString());
                     coord = new Coordinates(c[0],c[1], 0);
                     break;
             }

            //Waypoint wp = new Waypoint();
            //wp = new Waypoint(nameField.getText(), coord.getLatitude(), coord.getLongitude(), coord.getAltitude());
            currentWaypoint.setName(nameField.getText());
            currentWaypoint.setLatitude(coord.getLatitude());
            currentWaypoint.setLongitude(coord.getLongitude());
            currentWaypoint.setAltitude(coord.getAltitude());
            
             WaypointsDAO dao = new WaypointsDAO();
             dao.storeWaypoint (currentWaypoint);
    }

    public MenuItem aboutMenuItem = new MenuItem("About", 3,3){
        public void run(){
            Dialog.inform("This application has been designed for non-commercial use. Any queries please contact me via paul.haenel@gmail.com!");
        }
    };

    public MenuItem exitMenuItem = new MenuItem("Exit", 4,4){
        public void run(){ System.exit(1); }
    };

    protected void makeMenu(Menu menu, int instance){
        menu.add(storeMenuItem);
        menu.add(aboutMenuItem);
        menu.add(exitMenuItem);
    }

}

